package com.yxjx.duoxue;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;

import com.yxjx.duoxue.customview.MyProgressDialog;
import com.yxjx.duoxue.customview.YxListView;
import com.yxjx.duoxue.database.YxDataBase;
import com.yxjx.duoxue.datamodel.DMCallRecord;
import com.yxjx.duoxue.datamodel.DMReportErrorItem;
import com.yxjx.duoxue.datamodel.ResponseObject;
import com.yxjx.duoxue.global.Globals;
import com.yxjx.duoxue.network.MsgCode;
import com.yxjx.duoxue.network.NwUtils;
import com.yxjx.duoxue.utils.UIHelper;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class ReportErrorDialogHelper {

	public static final int MSG_CODE_REPORT_ERROR_LIST_LOAD_DONE = 1;
	public static final int MSG_CODE_SUBMIT_ERROR_REPORT_DONE = 2;

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_CODE_REPORT_ERROR_LIST_LOAD_DONE:
				onLoadListDone();
				break;
			case MSG_CODE_SUBMIT_ERROR_REPORT_DONE:
				if (progressDialog != null) {
					progressDialog.dismiss();
					progressDialog = null;
				}
				ResponseObject code = (ResponseObject) msg.obj;
				if (code.getCode() == MsgCode.SUCCESS) {
					if (alertDialog != null) {
						alertDialog.dismiss();
						alertDialog = null;
					}
					UIHelper.showTips(mRoot, "提交成功");
				} else {
					UIHelper.showTips(mRoot, "提交失败，" + MsgCode.descFor(code));
				}
				break;
			default:
				break;
			}
		};
	};
	private MyAdapter mAdapter;
	private Context mContext;
	private FrameLayout mRoot;
	protected ProgressDialog progressDialog;
	private int mType;
	private String mTypeId;
	private AlertDialog alertDialog;
	
	public ReportErrorDialogHelper(Context context) {
		mContext = context;
	}

	/**
	 * 弹出用户错误反馈对话框
	 * @param type
	 * @param typeId
	 */
	public void show(int type, String typeId) {
		// 重置错误列表
		ArrayList<DMReportErrorItem> errorList = getErrorList();
		if (errorList != null) {
			for (DMReportErrorItem item : errorList) {
				item.setSelected(false);
			}
		}
		
		mType = type;
		mTypeId = typeId;
		mRoot = (FrameLayout) LayoutInflater.from(mContext).inflate(
				R.layout.segment_report_error_list, null);
		
		showLoading(true);

		if (errorList == null || errorList.size() == 0) {
			new Thread(new Runnable() {

				@Override
				public void run() {
					ArrayList<DMReportErrorItem> list;
					try {
						list = NwUtils.requestReportErrorItemList(mContext);
						Globals.getInstance(mContext).setErrorList(list);
					} catch (ClientProtocolException e) {
						e.printStackTrace();
					} catch (ParseException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					} catch (JSONException e) {
						e.printStackTrace();
					} finally {
						handler.sendEmptyMessage(MSG_CODE_REPORT_ERROR_LIST_LOAD_DONE);
					}
				}
			}).start();
		} else {
			handler.sendEmptyMessage(MSG_CODE_REPORT_ERROR_LIST_LOAD_DONE);
		}

		YxListView listView = (YxListView) mRoot.findViewById(R.id.list);
		mAdapter = new MyAdapter();
		listView.setAdapter(mAdapter);
		alertDialog = new AlertDialog.Builder(mContext)
				// 在这里把写好的这个listview的布局加载dialog中
				.create();
		alertDialog.setCanceledOnTouchOutside(true);// 使除了dialog以外的地方不能被点击

		alertDialog.show();
		alertDialog.getWindow().setContentView(mRoot);
		alertDialog.getWindow().setGravity(Gravity.BOTTOM);
		listView.setOnItemClickListener(new OnItemClickListener() {// 响应listview中的item的点击事件

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				ArrayList<DMReportErrorItem> list = getErrorList();
				boolean state = list.get(arg2).isSelected();
				list.get(arg2).setSelected(!state);
				for (int i = 0; i < list.size(); i++) {
					if (list.get(arg2).isSelected() && i != arg2) {
						list.get(i).setSelected(false);
					}
				}
				mAdapter.notifyDataSetInvalidated();
			}
		});
		
		UIHelper.setClickListener(mRoot, R.id.submit, new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				submit();
				
			}
		});
	}

	private ArrayList<DMReportErrorItem> getErrorList() {
		return Globals.getInstance(mContext).getErrorList();
	}
	
	private void submit() {
		
		final ArrayList<DMReportErrorItem> errorList = getErrorList();
		int choosen = -1;
		for (int i = 0; errorList != null && i < errorList.size(); i++) {
			if (errorList.get(i).isSelected()) {
				choosen = i;
				break;
			}
		}
		if (choosen < 0) {
			UIHelper.showTips(mRoot, "请选择错误类型");
			return;
		}
		
		progressDialog = MyProgressDialog.show(mContext, "", "正在提交");
		final int finalChoosen = choosen;
		new Thread(new Runnable() {
			@Override
			public void run() {
				ResponseObject code = new ResponseObject(-1, "");
				try {
					code = NwUtils.submitReprotError(mContext, errorList.get(finalChoosen).getId(), mType, mTypeId);
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (ParseException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (JSONException e) {
					e.printStackTrace();
				} finally {
					Message msg = handler.obtainMessage(MSG_CODE_SUBMIT_ERROR_REPORT_DONE, code);
					handler.sendMessage(msg);
				}
			}
		}).start();
	}
	
	/**
	 * @param showLoading
	 */
	private void showLoading(boolean showLoading) {
		mRoot.findViewById(R.id.list_root).setVisibility(showLoading ? View.INVISIBLE : View.VISIBLE);
		mRoot.findViewById(R.id.loading).setVisibility(showLoading ? View.VISIBLE : View.INVISIBLE);
	}
	
	protected void onLoadListDone() {
		mAdapter.notifyDataSetChanged();
		showLoading(false);
	}

	class MyAdapter extends BaseAdapter {
		
		@Override
		public int getCount() {
			ArrayList<DMReportErrorItem> errorList = Globals.getInstance(mContext).getErrorList();
			return errorList == null ? 0 : errorList.size();
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			View ret = null;
			if (arg1 == null) {
				ret = LayoutInflater.from(mContext).inflate(R.layout.item_error_report_list, null);
			} else {
				ret = arg1;
			}
			ArrayList<DMReportErrorItem> errorList = Globals.getInstance(mContext).getErrorList();
			DMReportErrorItem item = errorList.get(arg0);
			UIHelper.setText(ret, R.id.text, item.getName());
			ret.findViewById(R.id.icon).setSelected(item.isSelected());
			return ret;
		}
	}
}
